<?php
require_once("../core/public.php");
use \core\Db;
//权限检测
if(isGet() && checkAuth(1)==false){
    require_once '../public/403.html';
    exit();
}elseif (isPost()){
    if(checkAuth(1)==false){
        response_error();
    }else{
        $action = param('action');
        switch ($action){
            case "detail":
                $id = post('id');
                $row = Db::connect()->table('category')->where(['id'=>$id])->find();
                if($row){
                    json_success("Ok",$row);
                }else{
                    json_error("数据不存在");
                }
                break;
            case "list":
                //数据查询
                $page = post('page');
                $userRows = Db::connect()->table('category')->page($page,15)->select();
                response_data($userRows,Db::connect()->table('category')->count());
                break;
            case "add":
                $data = post('data');
                $row = Db::connect()->table('category')->where(['name'=>$data['name']])->find();
                if($row){
                    json_error("分类【".$data['name']."】已存在");
                }
                $result = Db::connect()->table('category')->insert($data);
                if($result){
                    json_success("添加成功");
                }else{
                    json_error("添加失败");
                }
                break;
            case "edit":
                $data = post('data');
                $id = post('id');

                unset($data['id']);

                $result = Db::connect()->table('category')->update($data,["id"=>$id]);
                if($result){
                    json_success("修改成功");
                }else{
                    json_error("修改失败");
                }
                break;
            case "del":
                $ids = post('ids');
                $ids_string  = implode(',',$ids);
                $result = Db::connect()->table('category')->delete(["id in (".$ids_string.")"]);
                if($result){
                    json_success("删除成功");
                }else{
                    json_error("删除失败");
                }
                break;
            case "setField":
                $field = post('field');
                $value = post('value');
                $ids = post('ids');

                if($field=="role" && $value==1){
                    $ids = array_diff($ids,[1]);
                    if(count($ids)==0){
                        json_error("超级管理员不能设置为普通用户");
                    }
                }

                $ids_string  = implode(',',$ids);
                $result = Db::connect()->table('category')->update([$field=>$value],["id in (".$ids_string.")"]);
                if($result){
                    json_success("设置成功");
                }else{
                    json_error("设置失败");
                }
                break;
            default:
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>反馈分类</title>
    <link rel="stylesheet" href="/public/plugins/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/public/css/common.css" media="all">
    <script src="/public/plugins/layui/layui.js"></script>
    <script src="/public/js/public.js"></script>
</head>
<body>
<blockquote class="layui-elem-quote layui-quote-nm">反馈分类</blockquote>
<div class="table-cc">
    <table class="layui-table" lay-filter="user-table" id="user-table"></table>
</div>

<form class="layui-form layui-hide" action="" id="formAdd" style="padding: 20px" lay-filter="formAddEdit">
    <input type="hidden" name="id">
    <div class="layui-form-item">
        <label class="layui-form-label">名称</label>
        <div class="layui-input-block">
            <input type="text" name="name" required  lay-verify="required" placeholder="请输入名称" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">状态</label>
        <div class="layui-input-block">
            <input type="radio" name="status" value="1" title="启用" checked>
            <input type="radio" name="status" value="0" title="禁用">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="formAddEdit">提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>

<script type="text/html" id="user-toolbar">
    <div class="layui-btn-container wycto-admin-toolbar-container">
        <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="add">
            <i class="layui-icon layui-icon-edit"></i>
            <span class="wycto-btn-text">添加</span>
        </button>
        <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="del">
            <i class="layui-icon layui-icon-edit"></i>
            <span class="wycto-btn-text">删除</span>
        </button>
        <button class="layui-btn layui-btn-sm" lay-event="setField" data-field="status" data-value="1">
            <i class="layui-icon layui-icon-set"></i>
            <span class="wycto-btn-text">启用</span>
        </button>
        <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="setField" data-field="status" data-value="0">
            <i class="layui-icon layui-icon-set"></i>
            <span class="wycto-btn-text">禁用</span>
        </button>
    </div>
</script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
</script>
<script>
    layui.use(['table','form'], function(){
        var table = layui.table,$ = layui.$,form = layui.form;

        //第一个实例
        tableIns = table.render({
            elem: '#user-table'
            ,title:"用户管理"
            ,url: '/admin/category.php?action=list' //数据接口
            ,page: true //开启分页
            ,method: 'POST'
            ,cellMinWidth: 10
            ,even: true //开启隔行背景
            ,autoSort: false //禁用前端自动排序。注意：该参数为 layui 2.4.4 新增
            ,toolbar: '#user-toolbar' //开启头部工具栏，并为其绑定左侧模板
            ,cols: [[ //表头
                {type: 'checkbox', fixed: 'left',field:'id'}
                ,{type: 'numbers', fixed: 'left',title:'序号'}
                ,{field: 'name', title: '名称'}
                ,{field: 'status', title: '状态',templet:function (d) {return formatStatus(d.status);}}
                ,{field: 'op', title: '操作',toolbar:'#barDemo'}
            ]]
        });

        //头工具栏事件
        table.on('toolbar(user-table)', function(obj){
            var dataset = obj.config.elem.context.activeElement.dataset;
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case "add":
                    form.val("formAddEdit", {name:'',id:'',status:1});
                    $("#formAdd").removeClass('layui-hide');
                    layer.open({
                        type: 1,
                        skin: 'layui-layer-rim', //加上边框
                        area: ['600px', '400px'], //宽高
                        content: $('#formAdd'),
                        cancel: function(index, layero){
                            $("#formAdd").addClass('layui-hide');
                            layer.close(index);
                            return false;
                        }
                    });
                    break;
                case 'del':
                    var data = checkStatus.data;
                    if(data.length<=0){
                        layer.alert('请勾选记录', {icon: 5});
                        return false;
                    }
                    var ids = [];
                    $(data).each(function(i) {
                        ids[i] = data[i]['id'];
                    });

                    $.post("", {ids:ids,action:'del'}, function(res) {
                        if (res.code) {
                            //询问框
                            tableIns.reload();
                            layer.msg(res.msg,{time:2000});
                        } else {
                            //信息框
                            layer.open({
                                content : res.msg,
                                btn : '我知道了'
                            });
                        }
                    },'json');
                    break;
                case 'setField':
                    var data = checkStatus.data;
                    if(data.length<=0){
                        layer.alert('请勾选要设置的记录', {icon: 5});
                        return false;
                    }
                    var ids = [];
                    $(data).each(function(i) {
                        ids[i] = data[i]['id'];
                    });

                    $.post("", {ids:ids,action:'setField',field:dataset.field,value:dataset.value}, function(res) {
                        if (res.code) {
                            //询问框
                            tableIns.reload();
                            layer.msg(res.msg,{time:2000});
                        } else {
                            //信息框
                            layer.open({
                                content : res.msg,
                                btn : '我知道了'
                            });
                        }
                    },'json');
                    break;
            };
        });

        //监听工具条
        table.on('tool(user-table)', function(obj){
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）

            if(layEvent === 'edit'){ //编辑
                //do something
                //给表单赋值
                form.val("formAddEdit", data);
                $("#formAdd").removeClass('layui-hide');
                layer.open({
                    type: 1,
                    skin: 'layui-layer-rim', //加上边框
                    area: ['600px', '400px'], //宽高
                    content: $('#formAdd'),
                    cancel: function(index, layero){
                        $("#formAdd").addClass('layui-hide');
                        layer.close(index);
                        return false;
                    }
                });
            }
        });

        //监听提交
        form.on('submit(formAddEdit)', function(data){
            var action = "add";
            var dataRow = data.field;
            if(dataRow.id){
                action = "edit";
            }else{
                delete dataRow.id
            }
            //layer.msg(JSON.stringify(data.field));
            $.post("", {action:action,data:data.field,id:dataRow.id}, function(res) {
                if (res.code) {
                    //询问框
                    tableIns.reload();
                    layer.msg(res.msg,{time:2000});
                    $("#formAdd").addClass('layui-hide');
                    layer.closeAll(); //疯狂模式，关闭所有层
                } else {
                    //信息框
                    layer.open({
                        content : res.msg,
                        btn : '我知道了'
                    });
                }
            },'json');
            return false;
        });
    });
</script>
</body>
</html>